import { toastMessage } from '@/utils/toast.js'



interface requestInt {
  url: string,
  method: 'GET' | 'POST',
  data: string | object | ArrayBuffer,
  options?: any,
}
 
class HttpRequest {
  request = (params: requestInt, showLoading: boolean ) => {
	
    let { url, method, data, options  } = params
    // uni.showLoading({
    //   title: '加载中...',
    //   mask: true
    // });
	// 显示加载中
	if (showLoading) {
	  uni.showLoading({
		title: '加载中...',
		mask: true
	  });
	}
	let token = uni.getStorageSync('token') ;
	
	if (token) {
		
	} else {
		// 如果没有 token，则跳转到登录页面
		// if (url !== '/doLogin' ) {
		// 	uni.navigateTo({
		// 		url: '/pages/login/login'
		// 	});
		// }
		
		const hasNoCall = url.includes("noCall");
		if(!hasNoCall){
			const hasDoLogin = url.includes("doLogin");
			if (!hasDoLogin) {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}
		}
	}
	//url: `${import.meta.env.VITE_APP_BASE_API}${url}`,
    return new Promise<any>((resolve, reject) => {
      uni.request({
        url: `${url}`,
        method,
        data,
        header: {
			'Content-Type': 'application/json',
			'token':token
		},
        success: (res: any) => {
			if (showLoading) {
				uni.hideLoading();
			}
			const data = res.data; 
			console.log(data);
			switch (res.statusCode) {
				case 200:
				if(data.code === 200 ||  data.code === 1000){
					resolve(data)
					break;
				}else if(data.code ===500){
					// console.log("=====");
					// toastMessage("登陆失效！");
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}else{
					toastMessage(data.msg == null ?  "未知异常，请稍后再试！" : data.msg);
					reject(data)
					break
				}
				
			}
        },
        fail: (err: any) => {
			if (showLoading) {
				uni.hideLoading();
			}
			toastMessage("接口异常，请稍后再试！");
			reject(err)
        }
      })
    })
  }
 
  // get请求
  get(url = '', data = {}, options = {}, showLoading = true) {
    return this.request({
      url,
      method: "GET",
      data,
      ...options
    },showLoading);
  }
 
  // post请求
  post(url = '', data = {}, options = {}, showLoading = true) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    },showLoading);
  }
 
}
 
export default new HttpRequest(); 